<template>
	<el-dialog
	  title="发起"
	  :visible.sync="visible"
	  :before-close="close"
	  :close-on-click-modal="false"
    append-to-body
	  width="50%">

    <el-card>
      <el-form label-position="right" label-width="100px">
        <el-form-item label="货品名称:">
          <el-autocomplete
            v-if="!isSelect"
            v-model="dataForm.productName"
            :clearable="true"
            :fetch-suggestions="searchSpecialProduct"
            placeholder="货品名称"
            :trigger-on-focus="false"
            @select="selectSpecialProduct"
            style="width: 91%;">
              <template slot-scope="{ item }">
                <div class="name">{{ item.productName }}</div>
                <span class="pot">{{ (item.productGmp == null ? '' : ('编码:'+item.productGmp)) + ' ' + (item.productSpec == null ? '' : ('规格:'+item.productSpec)) }}</span>
              </template>
            </el-autocomplete>
          <span v-else>
            <span>{{ dataForm.productName }}</span>
            <el-button
              type="info"
              class="pan-btn info-btn"
              @click="showProductSelect"
              size="mini">
              选择货品
            </el-button>
          </span>
          <el-tooltip effect="dark" :content="isSelect ? '改为填写' : '改为选择'" placement="top">
            <el-switch
              style="margin-left: 20px"
              v-model="isSelect"
              @change="changeProductSelect"
              active-color="#7cbd36"
              inactive-color="#ff4949">
            </el-switch>
          </el-tooltip>
        </el-form-item>

        <el-form-item label="货品规格:">
          <el-input v-if="!isSelect" placeholder="货品规格" v-model="dataForm.productSpec" :clearable="true" />
          <span v-else v-html="dataForm.productSpec" />
        </el-form-item>

        <el-form-item label="物料编码:">
          <el-input v-if="!isSelect" placeholder="物料编码" v-model="dataForm.productGmp" :clearable="true" />
          <span v-else>{{ dataForm.productGmp }}</span>
        </el-form-item>

        <el-form-item label="分发日期:" prop="sendTime">
          <el-date-picker
            v-model="dataForm.sendTime"
            align="right"
            type="date"
            placeholder="选择日期"
            style="width: 100%;"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd HH:mm:ss" />
        </el-form-item>

        <el-form-item label="项目列表:">
          <div v-for="(s ,i) in dataForm.standardList"
            :key="i"
            :prop="'dataForm.standardList.' + i + 'selectItems'">
            <el-select
              v-model="s.standard"
              @change="setStandard(i)"
              value-key="insideInspectionStandardId"
              filterable
              remote
              reserve-keyword
              :remote-method="(val) => searchStandard(val, i)"
              placeholder="标准列表"
              :loading="s.loading"
              style="width: 50%;">
              <el-option
                v-for="item in s.candidate"
                :key="item.insideInspectionStandardId"
                :label="item.accordingToInside"
                :value="item">
              </el-option>
            </el-select>
            <el-select
              @change="setSelectItems(i)"
              v-model="s.selectItems"
              collapse-tags
              value-key="inspectionItemId"
              multiple
              filterable
              placeholder="项目选择"
              style="width: 43%">
              <el-option
                v-for="item in s.standard.items"
                :key="item.inspectionItemId"
                :label="item.inspectionItemName"
                :value="item">
              </el-option>
            </el-select>
            <el-button type="warning" class="pan-btn warning-btn" icon="el-icon-minus" @click="subStandard(i)" circle size="mini" />
          </div>
          <el-button type="warning" class="pan-btn warning-btn" icon="el-icon-plus" @click="addStandard" circle size="mini" />
        </el-form-item>

        <el-form-item label="公共项目:">
          <el-select
            v-model="dataForm.selectSpecialItems"
            value-key="specialInspectionItemId"
            multiple
            filterable
            placeholder="公共项目选择"
            style="width: 80%">
            <el-option
              v-for="item in specialItems"
              :key="item.specialInspectionItemId"
              :label="item.inspectionItemName + '【' + (item.remark == null ? '' : ('备注：' + item.remark)) + '，检验组：' + item.inspectionGroupName + '】'"
              :value="item">
            </el-option>
          </el-select>
          <el-button type="warning" class="pan-btn warning-btn" icon="el-icon-plus" @click="showAddSpecialItem" circle size="mini" />
          <el-button type="info" class="pan-btn info-btn" @click="showSpecialItem" icon="el-icon-s-grid">去修改</el-button>
        </el-form-item>

        <el-form-item label="批号列表:">
          <div v-for="(b ,i) in dataForm.batchNumList"
            :key="i"
            :prop="'dataForm.batchNumList.' + i + 'value'">
            <el-input placeholder="批号列表" v-model="b.value" :clearable="true" style="width: 50%;" />
            <el-input placeholder="每批次数" @change="setCount(i)" v-model="b.count" :clearable="true" style="width: 43%;" />
            <el-button type="warning" class="pan-btn warning-btn" icon="el-icon-minus" @click="subBatch(i)" circle size="mini" />
          </div>
          <el-button type="warning" class="pan-btn warning-btn" icon="el-icon-plus" @click="addBatch" circle size="mini" />
          <el-button type="text" @click="multipleBatch" size="mini">倍数</el-button>
        </el-form-item>

        <el-form-item label="总计次数:">
          {{ totalCount }}
        </el-form-item>

        <el-form-item label="生产车间:">
          <el-select v-model="dataForm.workshop" value-key="workshopId" @change="setWorkshop" style="width: 100%;" filterable placeholder="生产车间">
            <el-option
              v-for="item in workshopList"
              :key="item.workshopId"
              :label="item.workshopName"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="生产企业:">
          <el-select
            v-model="dataForm.manufacturer"
            value-key="manufacturerId"
            @change="setManufacturer"
            filterable
            remote
            reserve-keyword
            :remote-method="searchManufacturer"
            placeholder="关键词搜索"
            :loading="manufacturerLoading"
            style="width: 100%">
            <el-option
              v-for="item in manufacturerList"
              :key="item.manufacturerId"
              :label="item.manufacturerName"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="供应商:">
          <el-select
            v-model="dataForm.supplier"
            value-key="supplierId"
            @change="setSupplier"
            filterable
            remote
            reserve-keyword
            :remote-method="searchSupplier"
            placeholder="关键词搜索"
            :loading="supplierLoading"
            style="width: 100%">
            <el-option
              v-for="item in supplierList"
              :key="item.supplierId"
              :label="item.supplierName"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="备注:">
          <el-input type="textarea" placeholder="备注" autosize v-model="dataForm.remark" :clearable="true" />
        </el-form-item>
      </el-form>
    </el-card>

    <product-select
      @getProduct="getProduct"
      @showProductSelect="showProductSelect"
      :childDataForm="childDataForm"
      v-if="productSelectVisible" />

    <el-dialog
      title="新增公共项目"
      :visible.sync="addSpecialItemVisible"
      :before-close="closeInner"
      append-to-body
      :close-on-click-modal="false"
      width="30%">
      <el-card>
        <el-form label-position="top">
          <el-form-item label="检验项目">
            <el-input placeholder="项目名称" v-model="specialItemForm.inspectionItemName" :clearable="true" />
          </el-form-item>
          <el-form-item label="所属小组">
            <el-select v-model="specialItemForm.inspectionGroup" @change="setInspectionGroup" value-key="inspectionGroupId" filterable placeholder="所属小组" style="width: 100%;">
              <el-option
                v-for="group in groupList"
                :key="group.inspectionGroupId"
                :label="group.inspectionGroupName"
                :value="group">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="标准工时1">
          	<el-input v-model="specialItemForm.manHourOne" placeholder="标准工时1">
              <template slot="append">小时</template>
            </el-input>
          </el-form-item>
          <el-form-item label="标准工时2">
          	<el-input v-model="specialItemForm.manHourTwo" placeholder="标准工时2">
              <template slot="append">小时</template>
            </el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input placeholder="备注" v-model="specialItemForm.remark" :clearable="true" />
          </el-form-item>
        </el-form>
      </el-card>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeInner">取 消</el-button>
        <el-button type="primary" :loading="submitingAddSpecialItem" @click="submitAddSpecialItem">确 定</el-button>
    	</span>
    </el-dialog>

	  <span slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button class="pan-btn primary-btn" type="primary" :loading="submiting" @click="submit">确 定</el-button>
  	</span>

    <special-module
      v-if="specialItemVisible"
      @refreshData="getSpecialItems"
      @close="showSpecialItem" />

	</el-dialog>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { getWorkshopList,saveCheckPerformances } from '@/api/check'
  import { getStandardList } from '@/api/standard'
  import { getSpecialItems,saveOrUpdateSpecialItem } from '@/api/item'
  import { querySpecialProductByName } from '@/api/product'
  import { getGroupList } from '@/api/inspection'
  import { getSupplierList } from "@/api/supplier"
  import { getManufacturerList } from "@/api/manufacturer"
  import { CODE_OK } from '@/common/js/config'
  import { isBlank,parseTime } from '@/common/js/utils'
  import ProductSelect from '@/views/modules/base/product-select'
  import { isPositiveIntegerNumber } from '@/common/js/validate'
  import SpecialModule from '@/views/modules/base/hour-special'
  import Calc from 'calculatorjs'
  export default {
  	data() {
  		return {
  			visible: false,
        isSelect: true,
        productSelectVisible: false,
        addSpecialItemVisible: false,
        submitingAddSpecialItem: false,
        submiting: false,
        workshopList: [],
        manufacturerList: [],
        supplierList: [],
        supplierLoading: false,
        manufacturerLoading: false,
        specialItems: [],
        dataForm: {
          productId: null,
          specialProductId: null,
          productName: null,
          productGmp: null,
          productSpec: null,
          standardList: [{
            loading: false,
            candidate: [],
            standard: {
              insideInspectionStandardId: null,
            },
            selectItems: []
          }],
          batchNumList: [{
            value: null,
            count: 1
          }],
          selectSpecialItems: [],
        },
        childDataForm: '',
        specialItemForm: {},
        groupList: [],
        specialItemVisible: false
  		}
  	},
  	created() {
      this.getInfo()
  		this.visible = true
  	},
    components: {
    	ProductSelect,SpecialModule
    },
    computed: {
      ...mapGetters([
         'userInfo'
      ]),
      totalCount() {
        let t = 0
        for (let i=0,j=this.dataForm.batchNumList.length; i<j; i++) {
          if (isPositiveIntegerNumber(this.dataForm.batchNumList[i].count)) {
            t = Calc(t + '+' +  this.dataForm.batchNumList[i].count)
          }
        }
        return t
      }
    },
  	methods: {
      showSpecialItem() {
        this.specialItemVisible = !this.specialItemVisible
      },
      submitAddSpecialItem() {
        this.submitingAddSpecialItem = true
        if (isBlank(this.specialItemForm.inspectionItemName)) {
          this.$message.error('名称不能为空')
          return
        }
        if (isBlank(this.specialItemForm.inspectionGroupId)) {
          this.$message.error('请选择所属小组')
          return
        }
        if (!isBlank(this.specialItemForm.manHourOne)) {
          if (!isPositiveIntegerNumber(this.specialItemForm.manHourOne)) {
            this.$message.error('标准工时1必须为正整数或者为空')
            return
          }
        }
        if (!isBlank(this.specialItemForm.manHourTwo)) {
          if (!isPositiveIntegerNumber(this.specialItemForm.manHourTwo)) {
            this.$message.error('标准工时1必须为正整数或者为空')
            return
          }
        }
        saveOrUpdateSpecialItem(this.specialItemForm).then(res => {
          if (res.code === CODE_OK) {
            this.$message.success('添加成功')
            this.specialItemForm = res.item
            this.specialItems.push(this.specialItemForm)
            this.specialItemForm = {}
            this.closeInner()
          }else{
            this.$message.error(res.msg)
          }
          this.submitingAddSpecialItem = false
        })
      },
      setInspectionGroup() {
        this.specialItemForm.inspectionGroupId = this.specialItemForm.inspectionGroup.inspectionGroupId
        this.specialItemForm.inspectionGroupName = this.specialItemForm.inspectionGroup.inspectionGroupName
      },
      showAddSpecialItem() {
        this.addSpecialItemVisible = true
      },
      selectSpecialProduct(p) {
        this.dataForm.specialProductId = p.specialProductId
        this.dataForm.productName = p.productName
        this.dataForm.productGmp = p.productGmp
        this.dataForm.productSpec = p.productSpec
      },
      searchSpecialProduct(name, cb) {
        if (!isBlank(name)) {
          const params = {
            productName: name
          }
          querySpecialProductByName(params).then(res => {
            if (res.code === CODE_OK) {
              cb(res.list.map(p => {
                this.$set(p,'value',p.productName)
                return p
              }))
            }else{
              this.$message.error(res.msg)
            }
          })
        }
      },
      subStandard(i) {
        if (this.dataForm.standardList.length == 1) {
          this.$message.error('标准列表至少有一个，且检测项目不能为空')
          return
        }
        this.dataForm.standardList.splice(i,1)
      },
      addStandard() {
        this.dataForm.standardList.push({
          loading: false,
          candidate: [],
          standard: {
            insideInspectionStandardId: '',
          },
          selectItems: []
        })
      },
      setSelectItems(i) {
        let isAllTest = this.dataForm.standardList[i].selectItems.map(s => {return s.inspectionItemName}).indexOf('全选') > -1
        if (isAllTest) {
          this.dataForm.standardList[i].selectItems = this.dataForm.standardList[i].standard.items.filter(it => {return it.inspectionItemId != 0})
        }
      },
      setStandard(i) {
        this.dataForm.standardList[i].selectItems = []
        if (this.dataForm.standardList.length == 1) return
        let si = this.dataForm.standardList.splice(i,1)[0]
        let repet = false
        for (let s of this.dataForm.standardList) {
          if (si.standard.insideInspectionStandardId == s.standard.insideInspectionStandardId) {
            repet = true
            break
          }
        }
        if (repet) {
          si = {
            loading: false,
            candidate: [],
            standard: {
              insideInspectionStandardId: '',
            },
            selectItems: []
          }
          this.$message.error('请勿添加重复标准')
        }
        this.dataForm.standardList.splice(i,0,si)
      },
      searchSupplier(query) {
        this.supplierLoading = true
        this.supplierList = []
        if (!isBlank(query)) {
          const params = {
          	page: 1,
            limit: 10,
          	supplierName: query
          }
          getSupplierList(params).then(res => {
            if (res.code === CODE_OK) {
              this.supplierList = res.page.list
            }else{
              this.$message.error(res.msg)
            }
            this.supplierLoading = false
          })
        }
      },
      searchManufacturer(query) {
        this.manufacturerLoading = true
        this.manufacturerList = []
        if (!isBlank(query)) {
          const params = {
            page: 1,
            limit: 10,
            manufacturerName: query
          }
          getManufacturerList(params).then(res => {
            if (res.code === CODE_OK) {
              this.manufacturerList = res.page.list
            }else{
              this.$message.error(res.msg)
            }
            this.manufacturerLoading = false
          })
        }
      },
      searchStandard(query, i) {
        this.dataForm.standardList[i].loading = true
        this.dataForm.standardList[i].candidate = []
        if (!isBlank(query)) {
          const params = {
            page: 1,
            limit: 99,
            accordingToInside: query
          }
          getStandardList(params).then(res => {
          	if (res.code === CODE_OK) {
          		this.dataForm.standardList[i].candidate = res.page.list.filter(s => {
                let it = JSON.parse(JSON.stringify(s.items[0]))
                it.inspectionItemId = 0
                it.inspectionItemName = '全选'
                s.items.unshift(it)
                return s.usable == 0
              })
          	}else{
          		this.$message.error(res.msg)
          	}
          	this.dataForm.standardList[i].loading = false
          }).catch()
        }
      },
      setCount(i) {
        if (!isPositiveIntegerNumber(this.dataForm.batchNumList[i].count)) {
          this.$message.error('请输入正整数')
          this.dataForm.batchNumList[i].count = 1
          return
        }
      },
      subBatch(i) {
        if (this.dataForm.batchNumList.length == 1) {
          this.$message.error('至少有一个批号，但是可以为空')
          return
        }
        this.dataForm.batchNumList.splice(i,1)
      },
      addBatch() {
        this.dataForm.batchNumList.push({
          value: this.dataForm.batchNumList[this.dataForm.batchNumList.length-1].value,
          count: 1
        })
      },
      multipleBatch() {
        this.$prompt('请输入倍数', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^([1-9]\d*|[0]{1,1})$/,
          inputErrorMessage: '正整数倍数'
        }).then(({ value }) => {
          for (let i=0,j=value-1; i<value-1; i++) {
            this.addBatch()
          }
        }).catch(() => {})
      },
      changeProductSelect() {
        this.dataForm.specialProductId = null
        this.dataForm.productId = null
        this.dataForm.productName = ''
        this.dataForm.productGmp = ''
        this.dataForm.productSpec = ''
      },
      showProductSelect() {
        this.productSelectVisible = !this.productSelectVisible
      },
      getProduct(p) {
        this.dataForm.productId = p.productId
        this.dataForm.productName = p.productName
        this.dataForm.productGmp = p.productGmp
        this.dataForm.productSpec = p.productSpec
        this.productSelectVisible = false
      },
      getInfo() {
        getWorkshopList().then(res => {
          if (res.code === CODE_OK) {
            this.workshopList = res.list
          }else{
            this.$message.error(res.msg)
          }
        })
        this.getSpecialItems()
        const params = {
          page: 1,
          limit: 99
        }
        getGroupList(params).then(res => {
        	if (res.code === CODE_OK) {
        		this.groupList = res.page.list.filter(g => {
              return g.inspectionGroupId != 1 && g.inspectionGroupId != 2
            })
        	}else{
            this.$message.error(res.msg)
          }
        })
      },
      getSpecialItems() {
        this.dataForm.selectSpecialItems = []
        getSpecialItems().then(res => {
          if (res.code === CODE_OK) {
            this.specialItems = res.list
          }else{
            this.$message.error(res.msg)
          }
        })
      },
      close(val) {
        if (val == 'submit') {
          this.$emit('refreshData')
        }
        this.$emit('close')
        this.visible = false
      },
      closeInner() {
        this.addSpecialItemVisible = false
      },
      submit() {
        this.submiting = true
        if (this.formVerify()) {
          //items
          let itemArr = []
          this.dataForm.standardList.forEach(s => {
            itemArr.push(...s.selectItems)
          })
          itemArr.push(...this.dataForm.selectSpecialItems)
          if (itemArr.length == 0) {
            this.$message.error('检验项目不能为空')
            return false
          }
          const checkPerformanceModel = {
            productId : this.dataForm.productId,
            specialProductId : this.dataForm.specialProductId,
            productName : this.dataForm.productName,
            productGmp : this.dataForm.productGmp,
            productSpec : this.dataForm.productSpec,
            batchNum : null,
            workshopId : this.dataForm.workshopId,
            workshopName : this.dataForm.workshopName,
            manufacturerId: this.dataForm.manufacturerId,
            manufacturerName: this.dataForm.manufacturerName,
            supplierId: this.dataForm.supplierId,
            supplierName: this.dataForm.supplierName,
            remark: this.dataForm.remark,
            inspectionItemId : null,
            specialInspectionItemId : null,
            inspectionGroupId : null,
            inspectionGroupName : null,
            inspectionItemName : null,
            manHourOne : null,
            manHourTwo : null,
            itemStatus : 1,
            sendTime : this.dataForm.sendTime,
            sendUserId : this.userInfo.userId,
            sendUserName : this.userInfo.name
          }
          //batchNum
          let batchNumArr = []
          this.dataForm.batchNumList.forEach(b => {
            for (let i=0,j=b.count; i<j; i++) {
              batchNumArr.push(b.value)
            }
          })
          //cps
          let checkPerformanceList = []
          for (let bn of batchNumArr) {
            let cp1 = JSON.parse(JSON.stringify(checkPerformanceModel))
            cp1.batchNum = bn
            for (let it of itemArr) {
              let cp2 = JSON.parse(JSON.stringify(cp1))
              cp2.inspectionItemId = it.inspectionItemId ? it.inspectionItemId : null
              cp2.specialInspectionItemId = it.specialInspectionItemId ? it.specialInspectionItemId : null
              cp2.inspectionGroupId = it.inspectionGroupId
              cp2.inspectionGroupName = it.inspectionGroupName
              cp2.inspectionItemName = it.inspectionItemName
              cp2.manHourOne = it.manHourOne
              cp2.manHourTwo = it.manHourTwo
              checkPerformanceList.push(cp2)
            }
          }
          saveCheckPerformances(checkPerformanceList).then(res => {
            if (res.code === CODE_OK) {
            	this.$message.success('发起成功')
              this.close('submit')
            }else{
              this.$message.error(res.msg)
            }
            this.submiting = false
          })
        }else{
          this.submiting = false
        }
      },
      formVerify() {
        if (isBlank(this.dataForm.productName)) {
          this.$message.error('货品名称不能为空')
          return false
        }
        if (isBlank(this.dataForm.sendTime)) {
          this.$message.error('分发日期不能为空')
          return false
        }
        if (this.dataForm.batchNumList.length != 1) {
          for (let b of this.dataForm.batchNumList) {
            if (isBlank(b.value)) {
              this.$message.error('批号列表有2个及以上时，任何批号不能为空')
              return false
            }
          }
        }
        return true
      },
      //set
      setWorkshop() {
        if (this.dataForm.workshop == null) {
          this.dataForm.workshopId = null
          this.dataForm.workshopName = null
        }else{
          this.dataForm.workshopId = this.dataForm.workshop.workshopId
          this.dataForm.workshopName = this.dataForm.workshop.workshopName
        }
      },
      setSupplier() {
        if (this.dataForm.supplier == null) {
          this.dataForm.supplierId = null
          this.dataForm.supplierName = null
        }else{
          this.dataForm.supplierId = this.dataForm.supplier.supplierId
          this.dataForm.supplierName = this.dataForm.supplier.supplierName
        }
      },
      setManufacturer() {
        if (this.dataForm.manufacturer == null) {
          this.dataForm.manufacturerId = null
          this.dataForm.manufacturerName = null
        }else{
          this.dataForm.manufacturerId = this.dataForm.manufacturer.manufacturerId
          this.dataForm.manufacturerName = this.dataForm.manufacturer.manufacturerName
        }
      }
    }
  }
</script>

<style scoped>
  >>> .el-form-item__content {
    line-height: 40px ;
  }
  li {
    line-height: normal;
    padding: 7px;
  }
  .name {
    text-overflow: ellipsis;
    overflow: hidden;
  }
  .pot {
    font-size: 12px;
    color: #b4b4b4;
  }

  .highlighted .pot {
    color: #ddd;
  }
</style>
